import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadFile } from 'element-plus'
import {
  Tools,
  Plus,
  Upload,
  Download,
  Refresh,
  ArrowDown,
  Document
} from '@element-plus/icons-vue'
import { formatDateTime } from '@/utils'
import type { InventoryDevice, InventoryDeviceQuery, InventoryDeviceForm, ImportResult } from '@/types/device'

export const useInventoryDevice = () => {
  const loading = ref(false)
  const submitting = ref(false)
  const importing = ref(false)
  const deviceDialogVisible = ref(false)
  const importDialogVisible = ref(false)
  const isEdit = ref(false)
  const selectedRows = ref<InventoryDevice[]>([])
  const selectedFile = ref<File | null>(null)
  const importResult = ref<ImportResult | null>(null)
  const deviceFormRef = ref<FormInstance>()
  const uploadRef = ref()

  // 搜索表单
  const searchForm = reactive<InventoryDeviceQuery>({
    keyword: '',
    status: undefined,
    wasteType: undefined,
    deviceType: undefined,
    warehouse: '',
    dateRange: []
  })

  // 分页信息
  const pagination = reactive({
    page: 1,
    size: 20,
    total: 0
  })

  // 库存统计
  const inventoryStats = reactive({
    totalCount: 245,
    totalTrend: '+15.2%',
    inStockCount: 178,
    inStockTrend: '+8.6%',
    maintenanceCount: 42,
    maintenanceTrend: '+3.2%',
    scrappedCount: 25,
    scrappedTrend: '-2.1%'
  })

  // 库存设备列表
  const inventoryList = ref<InventoryDevice[]>([])

  // 设备表单
  const deviceForm = reactive<InventoryDeviceForm>({
    code: '',
    wasteType: 'paper',
    deviceType: 'single',
    warehouse: '',
    purchaseDate: '',
    supplier: '',
    price: 0,
    remark: ''
  })

  // 表单验证规则
  const deviceRules: FormRules = {
    code: [
      { required: true, message: '请输入设备编号', trigger: 'blur' },
      { pattern: /^[A-Z0-9]{6,20}$/, message: '设备编号格式不正确', trigger: 'blur' }
    ],
    remark: [
      { required: false, message: '请输入设备名称', trigger: 'blur' }
    ],
    wasteType: [
      { required: true, message: '请选择回收类型', trigger: 'change' }
    ],
    deviceType: [
      { required: true, message: '请选择设备类型', trigger: 'change' }
    ],
    warehouse: [
      { required: false, message: '请输入仓库名称', trigger: 'blur' }
    ],

    purchaseDate: [
      { required: true, message: '请选择采购时间', trigger: 'change' }
    ]
  }

  // 获取回收类型标签
  const getWasteTypeTag = (type: string) => {
    switch (type) {
      case 'paper':
        return 'primary'
      case 'plastic':
        return 'success'
      case 'metal':
        return 'warning'
      case 'glass':
        return 'info'
      case 'textile':
        return ''
      case 'mixed':
        return 'danger'
      default:
        return 'info'
    }
  }

  // 获取回收类型文本
  const getWasteTypeText = (type: string) => {
    switch (type) {
      case 'paper':
        return '纸壳类'
      case 'fabric':
        return '织物类'
      case 'mixed':
        return '混合类'
      default:
        return '未知类型'
    }
  }

  // 获取状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case 'in_stock':
        return 'success'
      case 'out_stock':
        return 'warning'
      case 'scrap':
        return 'danger'
      default:
        return 'info'
    }
  }

  // 获取状态文本
  const getStatusText = (status: string) => {
    switch (status) {
      case 'in_stock':
        return '在库'
      case 'out_stock':
        return '出库'
      case 'scrap':
        return '报废'
      default:
        return '未知状态'
    }
  }

  // 加载库存设备列表
  const loadInventoryList = async () => {
    loading.value = true
    try {
      // 模拟演示数据
      const mockInventoryList: InventoryDevice[] = [
        {
          id: 1,
          code: 'INV001001',
          wasteType: 'paper',
          deviceType: 'single',
          warehouse: '合肥总仓',
          purchaseDate: '2024-01-15 09:00:00',
          supplier: '安徽智能设备有限公司',
          price: 12500.00,
          remark: '纸壳类专用回收设备，适用于办公室和学校',
          createdAt: '2024-01-15 09:00:00',
          updatedAt: '2024-01-15 09:00:00'
        },
        {
          id: 2,
          code: 'INV001002',
          wasteType: 'fabric',
          deviceType: 'double',
          warehouse: '合肥总仓',
          purchaseDate: '2024-01-20 14:30:00',
          supplier: '江苏环保科技',
          price: 15800.00,
          remark: '织物类专用回收设备',
          createdAt: '2024-01-20 14:30:00',
          updatedAt: '2024-01-20 14:30:00'
        },
        {
          id: 3,
          code: 'INV001003',
          wasteType: 'mixed',
          deviceType: 'double',
          warehouse: '合肥总仓',
          purchaseDate: '2024-01-10 11:00:00',
          supplier: '浙江环保设备厂',
          price: 14200.00,
          remark: '混合类回收多功能设备',
          createdAt: '2024-01-10 11:00:00',
          updatedAt: '2024-01-25 16:20:00'
        },
        {
          id: 4,
          code: 'INV001004',
          wasteType: 'paper',
          deviceType: 'single',
          warehouse: '合肥总仓',
          purchaseDate: '2024-02-01 16:00:00',
          supplier: '安徽智能设备有限公司',
          price: 12200.00,
          remark: '纸壳类标准回收设备',
          createdAt: '2024-02-01 16:00:00',
          updatedAt: '2024-02-01 16:00:00'
        },
        {
          id: 5,
          code: 'INV001005',
          wasteType: 'fabric',
          deviceType: 'single',
          warehouse: '合肥总仓',
          purchaseDate: '2024-02-10 10:30:00',
          supplier: '江苏环保科技',
          price: 9800.00,
          remark: '织物类小型回收设备',
          createdAt: '2024-02-10 10:30:00',
          updatedAt: '2024-02-10 10:30:00'
        },
        {
          id: 6,
          code: 'INV001006',
          wasteType: 'mixed',
          deviceType: 'double',
          warehouse: '合肥总仓',
          purchaseDate: '2024-02-15 14:20:00',
          supplier: '浙江环保设备厂',
          price: 14800.00,
          remark: '混合类多功能回收设备',
          createdAt: '2024-02-15 14:20:00',
          updatedAt: '2024-02-15 14:20:00'
        }
      ]

      // 模拟分页和搜索
      let filteredList = mockInventoryList

      // 应用搜索过滤
      if (searchForm.keyword) {
        filteredList = filteredList.filter(device =>
          device.code.includes(searchForm.keyword!) ||
          device.supplier.includes(searchForm.keyword!)
        )
      }

      if (searchForm.status) {
        filteredList = filteredList.filter(device => device.status === searchForm.status)
      }

      if (searchForm.wasteType) {
        filteredList = filteredList.filter(device => device.wasteType === searchForm.wasteType)
      }

      if (searchForm.deviceType) {
        filteredList = filteredList.filter(device => device.deviceType === searchForm.deviceType)
      }

      if (searchForm.warehouse) {
        filteredList = filteredList.filter(device =>
          device.warehouse.includes(searchForm.warehouse!)
        )
      }

      // 模拟分页
      const startIndex = (pagination.page - 1) * pagination.size
      const endIndex = startIndex + pagination.size
      const paginatedList = filteredList.slice(startIndex, endIndex)

      inventoryList.value = paginatedList
      pagination.total = filteredList.length

      // 更新统计数据
      inventoryStats.totalCount = mockInventoryList.length
      inventoryStats.inStockCount = mockInventoryList.filter(d => d.status === 'in_stock').length
      inventoryStats.maintenanceCount = mockInventoryList.filter(d => d.status === 'maintenance').length
      inventoryStats.scrappedCount = mockInventoryList.filter(d => d.status === 'scrapped').length

    } catch (error) {
      ElMessage.error('加载库存设备列表失败')
    } finally {
      loading.value = false
    }
  }

  // 搜索处理
  const handleSearch = () => {
    pagination.page = 1
    loadInventoryList()
  }

  // 重置处理
  const handleReset = () => {
    pagination.page = 1
    loadInventoryList()
  }

  // 分页处理
  const handlePageChange = (page: number) => {
    pagination.page = page
    loadInventoryList()
  }

  const handleSizeChange = (size: number) => {
    pagination.size = size
    pagination.page = 1
    loadInventoryList()
  }

  // 选择处理
  const handleSelectionChange = (selection: InventoryDevice[]) => {
    selectedRows.value = selection
  }

  // 新增设备
  const handleAddDevice = () => {
    isEdit.value = false
    Object.assign(deviceForm, {
      code: '',
      wasteType: 'paper',
      deviceType: 'single',
      warehouse: '',
      supplier: '',
      price: 0,
      purchaseDate: '',
      remark: ''
    })
    deviceDialogVisible.value = true
  }

  // 编辑设备
  const handleEdit = (row: InventoryDevice) => {
    isEdit.value = true
    Object.assign(deviceForm, row)
    deviceDialogVisible.value = true
  }

  // 设备表单提交
  const handleDeviceSubmit = async () => {
    if (!deviceFormRef.value) return

    try {
      await deviceFormRef.value.validate()
      submitting.value = true

      // 调用创建/更新设备API
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      deviceDialogVisible.value = false
      loadInventoryList()
    } catch (error) {
      ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    } finally {
      submitting.value = false
    }
  }

  // 批量导入
  const handleImport = () => {
    importDialogVisible.value = true
    selectedFile.value = null
    importResult.value = null
  }

  // 下载模板
  const downloadTemplate = () => {
    ElMessage.info('模板下载功能开发中...')
  }

  // 文件选择处理
  const handleFileChange = (file: UploadFile) => {
    selectedFile.value = file.raw as File
  }

  // 导入提交
  const handleImportSubmit = async () => {
    if (!selectedFile.value) {
      ElMessage.warning('请先选择文件')
      return
    }

    importing.value = true
    try {
      // 模拟导入过程
      await new Promise(resolve => setTimeout(resolve, 2000))

      // 模拟导入结果
      importResult.value = {
        success: 8,
        failed: 2,
        errors: [
          { row: 3, message: '设备编号已存在' },
          { row: 7, message: '采购价格格式错误' }
        ]
      }

      if (importResult.value.failed === 0) {
        ElMessage.success('导入成功')
        loadInventoryList()
      } else {
        ElMessage.warning(`导入完成，有 ${importResult.value.failed} 条记录失败`)
      }
    } catch (error) {
      ElMessage.error('导入失败')
    } finally {
      importing.value = false
    }
  }

  // 批量导出
  const handleExport = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要导出的设备')
      return
    }

    ElMessage.info(`导出 ${selectedRows.value.length} 条记录功能开发中...`)
  }

  // 批量维护
  const handleBatchMaintenance = async () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要维护的设备')
      return
    }

    try {
      await ElMessageBox.confirm(
        `确定要将选中的 ${selectedRows.value.length} 台设备设置为维护状态吗？`,
        '批量维护',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )

      // 调用批量维护API
      ElMessage.success('批量设置维护成功')
      loadInventoryList()
    } catch (error) {
      // 用户取消
    }
  }

  // 更多操作
  const handleMoreAction = (row: InventoryDevice, command: string) => {
    switch (command) {
      case 'put_into_use':
        ElMessage.info('投入使用功能开发中...')
        break
      case 'maintenance':
        ElMessage.info('维护记录功能开发中...')
        break
      case 'scrap':
        ElMessage.info('报废处理功能开发中...')
        break
      case 'delete':
        ElMessage.info('删除设备功能开发中...')
        break
    }
  }

  onMounted(() => {
    loadInventoryList()
  })

  return {
    loading,
    submitting,
    importing,
    deviceDialogVisible,
    importDialogVisible,
    isEdit,
    selectedRows,
    selectedFile,
    importResult,
    deviceFormRef,
    uploadRef,
    searchForm,
    pagination,
    inventoryStats,
    inventoryList,
    deviceForm,
    deviceRules,
    getWasteTypeTag,
    getWasteTypeText,
    getStatusTag,
    getStatusText,
    loadInventoryList,
    handleSearch,
    handleReset,
    handlePageChange,
    handleSizeChange,
    handleSelectionChange,
    handleAddDevice,
    handleEdit,
    handleDeviceSubmit,
    handleImport,
    downloadTemplate,
    handleFileChange,
    handleImportSubmit,
    handleExport,
    handleBatchMaintenance,
    handleMoreAction
  }
}
